package com.example.service.impl;

import com.example.service.EmailService;
import com.example.util.RedisCache;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;

import static com.example.config.RabbitMqConfig.CHECK_EMAIL_QUEUE;
import static com.example.config.RabbitMqConfig.REGISTER_EMAIL_QUEUE;

/**
 * @author hlc
 * @version 1.0
 * @date 2022/10/22 21:20
 */
@Slf4j
@Service
public class EmailServiceImpl implements EmailService {
    private final JavaMailSender javaMailSender;
    private final RedisCache redisCache;

    public EmailServiceImpl(JavaMailSender javaMailSender, RedisCache redisCache) {
        this.javaMailSender = javaMailSender;
        this.redisCache = redisCache;
    }

    @Override
    @SneakyThrows
    @RabbitListener(queues = REGISTER_EMAIL_QUEUE)
    public void sendRegisterCode(Message message, Channel channel) {
        String email = new String(message.getBody());
        log.info("接收到消息注册邮件{}", email);
        sendEmailCode("static/register-mail-template.ftl", "register:", "注册验证码", email);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
    }

    @Override
    @SneakyThrows
    @RabbitListener(queues = CHECK_EMAIL_QUEUE)
    public void sendCheckCode(Message message, Channel channel) {
        String email = new String(message.getBody());
        log.info("接收到消息校验邮件{}", email);
        sendEmailCode("static/forget-mail-template.ftl", "check:", "忘记密码验证码", email);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
    }

    private void sendEmailCode(String path, String keyPrefix, String subject, String email) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        //获取验证码 存入redis
        int randomCode = (int) ((Math.random() * 9 + 1) * 100000);
        redisCache.setCacheObject(keyPrefix + email, randomCode, 5, TimeUnit.MINUTES);
        //邮箱发送内容组成
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setSubject(subject);
        helper.setText(buildContent(path, randomCode + ""), true);
        helper.setTo(email);
        helper.setFrom("博客" + '<' + "3041028072@qq.com" + '>');
        javaMailSender.send(message);
    }

    private String buildContent(String path, String title) {
        //加载邮件html模板
        Resource resource = new ClassPathResource(path);
        StringBuilder buffer = new StringBuilder();
        String line;
        try (
                InputStream inputStream = resource.getInputStream();
                BufferedReader fileReader = new BufferedReader(new InputStreamReader(inputStream))
        ) {
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            log.info("发送邮件读取模板失败{}", e.getMessage());
        }
        //替换html模板中的参数
        return MessageFormat.format(buffer.toString(), title);
    }
}
